package com.liu.qqRobot.poke.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.poke.entity.base.Poke;
import com.liu.mybatisPlus.poke.service.PokeService;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class RandomDuelHandler {

    @Resource
    private PokeService pokeService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        List<Poke> pokeList = pokeService.list();
        Poke poke = pokeList.get(RandomUtil.randomInt(pokeList.size()));
        redisTemplate.opsForValue().set(RedisKeyInterface.RANDOM_POKE_REDIS_KEY + groupId + userId, JSONUtil.toJsonStr(poke));
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("poke", poke);
        try {
            HtmlToImageUtils.htmlToImage("randomDuelPokeTemplate.html", templateParam, "src/main/resources/picture/randomPoke.png", 1100);
            File file = new File("src/main/resources/picture/randomPoke.png");
            String encode = Base64.encode(file);
            String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
            QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
            qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.RANDOM_DUEL);
        } catch (IOException | ParserConfigurationException | SAXException | TemplateException e) {
            log.error("获取随机宝可梦展示模板失败:{}", e.getMessage(), e);
//            QQClientUtils.sendGroupMsg("[CQ:at,qq=" + userId + "]\n获取捕捉宝可梦展示模板失败，请联系制作人", userId, groupId, isGroup);
        }
    }
}
